package utils

import (
	"crypto/rand"
	"fmt"
	"net"
	"net/http"
	"strings"
	"time"
)

func Uuid() string {

	data := make([]byte, 16)

	rand.Read(data)

	return fmt.Sprintf("%x", data)
}

func FilenamePrefix() string {

	data := make([]byte, 8)

	rand.Read(data)

	return fmt.Sprintf("%x", data)
}

func GenerateOrderNo() string {

	data := make([]byte, 8)

	rand.Read(data)

	// 2 + 14 + 16 = 32位的订单号
	return "SS" + time.Now().Format("20060102150405") + fmt.Sprintf("%x", data)
}

func ClientPublicIP(r *http.Request) string {

	var ip string
	for _, ip = range strings.Split(r.Header.Get("X-Forwarded-For"), ",") {
		ip = strings.TrimSpace(ip)
		if ip != "" && !HasLocalIpAddr(ip) {
			return ip
		}
	}
	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != "" && !HasLocalIpAddr(ip) {
		return ip
	}

	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		if !HasLocalIpAddr(ip) {
			return ip
		}
	}
	return ""
}

func HasLocalIpAddr(ip string) bool {

	return HasLocalIP(net.ParseIP(ip))
}

// HasLocalIP 检测 IP 地址是否是内网地址
func HasLocalIP(ip net.IP) bool {

	if ip.IsPrivate() {
		return true
	}
	return ip.IsLoopback()
}

func GenerateCode(count int8) string {

	data := make([]byte, count>>1)

	rand.Read(data)

	return fmt.Sprintf("%x", data)
}
